package ext.generic.part;

import com.ptc.netmarkets.model.NmException;
import com.ptc.netmarkets.util.beans.NmCommandBean;

import com.ptc.windchill.enterprise.part.commands.PartDocServiceCommand;

import ext.generic.part.BomObject;
import ext.com.iba.IBAUtil;

import ext.com.csm.CSMUtil;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import java.net.MalformedURLException;
import java.net.URL;

import java.rmi.RemoteException;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Locale;
import java.util.TreeMap;

import java.util.Vector;

import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import wt.csm.navigation.ClassificationNode;

import wt.doc.WTDocument;

import wt.epm.EPMDocument;

import wt.fc.Persistable;

import wt.fc.QueryResult;

import wt.fc.WTObject;

import wt.httpgw.GatewayServletHelper;
import wt.httpgw.URLFactory;

import wt.ixb.clientAccess.StandardIXBService;

import wt.method.RemoteAccess;
import wt.method.RemoteMethodServer;

import wt.org.WTPrincipal;

import wt.part.*;

import wt.session.SessionContext;
import wt.session.SessionHelper;

import wt.util.WTContext;
import wt.util.WTException;

import wt.util.WTProperties;
import wt.util.WTPropertyVetoException;
import wt.util.WTStandardDateFormat;

import wt.vc.VersionControlException;
import wt.vc.VersionControlHelper;
import wt.vc.config.ConfigSpec;
import wt.vc.views.View;
/**
 *针对产品或者不仅爱你,导出EXCEL格式报表的方法类
 */
public class ReportExporter
    implements RemoteAccess
{
    private static String CLASSNAME = ReportExporter.class.getName();
    private static boolean VERBOSE = false;
    private static WTProperties wtProperties = null;
    private static Hashtable clfNodePathCache = new Hashtable(); //分类节点缓存,key=分类节点oid; value=分类节点路径

    private String pPstr; //顶层部件代号
    private WTPart pPrt = null;
    private ConfigSpec configSpec = null;
    Hashtable partv;
    private Locale locale = null;
    private ArrayList arraylist;
    private ArrayList docArraylist;
    private String filename = "";
    NmCommandBean nmcommandbean = null;

    private int count = 0;
    private int step = 1;

    static
    {
        try
        {
            wtProperties = WTProperties.getLocalProperties();
            VERBOSE = wtProperties.getProperty("ext.generic.part.verbose", false);
        }
        catch (Throwable throwable)
        {
            throw new ExceptionInInitializerError(throwable);
        }
    }

    public ReportExporter()
    {
        super();
        arraylist = new ArrayList();
        docArraylist = new ArrayList();
        partv = new Hashtable();
    }

    /**
     *导出零部件报表至excel的具体实现方法
     * @param nmcommandbean
     * @return 可供下载的已导出数据的Excel文件下载地址
     * @throws WTException
     */
    public URL exportPartReportToExcel(NmCommandBean nmcommandbean)
        throws WTException
    {
        if (VERBOSE)
            System.out.println(">>>" + CLASSNAME + ".exportPartReportToExcel()");
        this.nmcommandbean = nmcommandbean;
        URL url = null;
        locale = nmcommandbean.getLocale();
        WTPart pPrt = (WTPart) nmcommandbean.getPrimaryOid().getRefObject();
        if (VERBOSE)
            System.out.println("	top part=" + pPrt.getDisplayIdentifier());
        try
        {
            View view = (View) pPrt.getView().getObject();
            WTPartConfigSpec config = WTPartHelper.service.findWTPartConfigSpec();
            WTPartStandardConfigSpec standardConfig = config.getStandard();
            try
            {
                standardConfig.setView(view);
                configSpec = standardConfig;
            }
            catch (WTPropertyVetoException wpve)
            {
                throw new WTException(wpve);
            }
            //获取数据
            Hashtable partsCache= new Hashtable();
            Quantity quantity = new Quantity();
            quantity.setAmount(1.0D);
            quantity.setUnit(QuantityUnit.EA);
            if (VERBOSE)
                System.out.println("ReportExporter.exportPartReportToExcel: start time: " + getCurrentTime("yyyyMMddHHmmssSSS"));
            traversePartStructure(pPrt.getNumber(), pPrt, quantity, partv, 0, partsCache);
            if (VERBOSE)
                System.out.println("ReportExporter.exportPartReportToExcel: end time: " + getCurrentTime("yyyyMMddHHmmssSSS"));
            //结束获取数据
            url = outputDatatoExcel();
        }
        catch (Exception exception)
        {
            throw new WTException(exception);
        }
        return url;
    }
    
    /**
     *导出零部件报表至excel的具体实现方法
     * @param nmcommandbean
     * @return 可供下载的已导出数据的Excel文件下载地址
     * @throws WTException
     */
    public URL exportPartReportToExcel(NmCommandBean nmcommandbean, ConfigSpec configSpec1)
        throws WTException
    {
        if (VERBOSE)
            System.out.println(">>>" + CLASSNAME + ".exportPartReportToExcel(NmCommandBean nmcommandbean, ConfigSpec configSpec1)");
        this.nmcommandbean = nmcommandbean;
        URL url = null;
        locale = nmcommandbean.getLocale();
        WTPart pPrt = (WTPart) nmcommandbean.getPrimaryOid().getRefObject();
        if (VERBOSE)
            System.out.println("        top part=" + pPrt.getDisplayIdentifier());
        try
        {
            configSpec = configSpec1;
            //获取数据
            Hashtable partsCache= new Hashtable();
            Quantity quantity = new Quantity();
            quantity.setAmount(1.0D);
            quantity.setUnit(QuantityUnit.EA);
            if (VERBOSE)
                System.out.println("ReportExporter.exportPartReportToExcel: start time: " + getCurrentTime("yyyyMMddHHmmssSSS"));
            traversePartStructure(pPrt.getNumber(), pPrt, quantity, partv, 0, partsCache);
            if (VERBOSE)
                System.out.println("ReportExporter.exportPartReportToExcel: end time: " + getCurrentTime("yyyyMMddHHmmssSSS"));
            //结束获取数据
            url = outputDatatoExcel();
        }
        catch (Exception exception)
        {
            throw new WTException(exception);
        }
        return url;
    }

    /**
     *根据产品结构递归获取报表所需数据
     * @param pathPartNumber
     * @param wtPartParent
     * @param quantityParent
     * @param partv
     * @param level
     * @param partsCache
     * @throws WTException
     * @throws WTPropertyVetoException
     * @throws RemoteException
     * @throws IOException
     * @throws Exception
     */
    public void traversePartStructure(String pathPartNumber, WTPart wtPartParent, Quantity quantityParent, Hashtable partv, int level, Hashtable partsCache)
        throws WTException, WTPropertyVetoException, RemoteException, IOException
    {
        if (VERBOSE)
            System.out.println("ReportExporter.traversePartStructure: part = " + wtPartParent.getDisplayIdentifier());

        boolean ifexist = false;
        String value = "";

        //将顶层父件加入到哈西表中
        if (level == 0)
        {
            BomObject pbomobject = new BomObject();
            pbomobject = setBomObject(wtPartParent, quantityParent, null, partsCache);

            //将顶层部件对象放入哈西表
            pathPartNumber = wtPartParent.getNumber();
            arraylist.add(pathPartNumber);

            Hashtable hs = new Hashtable();
            //hs.put("BOMOBJECT",pbomobject);
            //hs.put("PATHFATHERS",new Hashtable());
            hs.put("SUMQUANTITY", new Double(0));
            Hashtable pathfathers = new Hashtable();
            Hashtable bomInfo = new Hashtable();
            bomInfo.put("BOMOBJECT", pbomobject);
            bomInfo.put("AMOUNT", "");
            pathfathers.put(" ", bomInfo);
            hs.put("PATHFATHERS", pathfathers);

            partv.put(pathPartNumber, hs);
            level++;

            QueryResult qr1 = PartDocServiceCommand.getAssociatedCADDocuments(wtPartParent);
            QueryResult qr2 = PartDocServiceCommand.getAssociatedDescribeDocuments(wtPartParent);

            String pathPartName = wtPartParent.getName();
            if (VERBOSE)
            {
                System.out.println("    got " + qr1.size() + " cad documents from the part " + wtPartParent.getIdentity());
                System.out.println("    got " + qr2.size() + " describing documents from the part " + wtPartParent.getIdentity());
            }
            while (qr1.hasMoreElements())
            {
                EPMDocument epm = (EPMDocument) qr1.nextElement();
                DocObject docobject = new DocObject();
                docobject = setDocObject(epm, pathPartNumber, pathPartName);
                docArraylist.add(docobject);
            }
            while (qr2.hasMoreElements())
            {
                WTDocument doc = (WTDocument) qr2.nextElement();
                DocObject docobject = new DocObject();
                docobject = setDocObject(doc, pathPartNumber, pathPartName);
                docArraylist.add(docobject);
            }
        }

        //得到所有和给定部件的WTPartUsageLink
        QueryResult uses = WTPartHelper.service.getUsesWTParts(wtPartParent, configSpec);
        while (uses.hasMoreElements())
        {
            Persistable[] element = (Persistable[]) uses.nextElement();
            WTPartUsageLink link = (WTPartUsageLink) element[0];
            WTPart wtPartSon = (WTPart) element[1];
            if (wtPartSon != null)
            {
                if (VERBOSE)
                    System.out.println("ReportExporter.traversePartStructure: wtPartSon = " + wtPartSon.getDisplayIdentifier());

                String partNumber = wtPartSon.getNumber();
                String partName = wtPartSon.getName();
                LineNumber lineNumber = link.getLineNumber();
                if (VERBOSE)
                    System.out.println("	line number=" + lineNumber);
                Quantity quantity = link.getQuantity();
                Double amount = new Double(quantity.getAmount());
                String samount = amount.toString();
                if ((samount.lastIndexOf(".0") != -1) && (samount.lastIndexOf(".0") + 2) == samount.length())
                    samount = samount.substring(0, samount.lastIndexOf(".0"));

                //如果哈西表中没有重复件
                if (!partv.containsKey(partNumber))
                {
                    if (VERBOSE)
                        System.out.println("	the part is new to the report.");
                    //声明子件BomObject对象
                    BomObject bomobject = null;
                    bomobject = setBomObject(wtPartSon, quantity, lineNumber, partsCache);

                    Hashtable hs = new Hashtable();
                    Hashtable pathfathers = new Hashtable();
                    //pathfathers.put(pathPartNumber,samount);
                    Hashtable bomInfo = new Hashtable();
                    bomInfo.put("BOMOBJECT", bomobject);
                    bomInfo.put("AMOUNT", samount);
                    pathfathers.put(pathPartNumber, bomInfo);

                    //hs.put("BOMOBJECT",bomobject);
                    hs.put("PATHFATHERS", pathfathers);
                    hs.put("SUMQUANTITY", new Double(quantityParent.getAmount() * quantity.getAmount()));

                    //将该件加入到哈西表中
                    partv.put(partNumber, hs);

                    arraylist.add(partNumber);
                    traversePartStructure(partNumber, wtPartSon, quantity, partv, level + 1, partsCache);

                    QueryResult qr1 = PartDocServiceCommand.getAssociatedCADDocuments(wtPartSon);
                    QueryResult qr2 = PartDocServiceCommand.getAssociatedDescribeDocuments(wtPartSon);
                    if (VERBOSE)
                    {
                        System.out.println("    got " + qr1.size() + " cad documents from the part " + wtPartSon.getIdentity());
                        System.out.println("    got " + qr2.size() + " describing documents from the part " + wtPartSon.getIdentity());
                    }
                    while (qr1.hasMoreElements())
                    {
                        EPMDocument epm = (EPMDocument) qr1.nextElement();
                        DocObject docobject = new DocObject();
                        docobject = setDocObject(epm, partNumber, partName);
                        docArraylist.add(docobject);
                    }
                    while (qr2.hasMoreElements())
                    {
                        WTDocument doc = (WTDocument) qr2.nextElement();
                        DocObject docobject = new DocObject();
                        docobject = setDocObject(doc, partNumber, partName);
                        docArraylist.add(docobject);
                    }
                }
                else //如果哈西表中有重复件
                {
                    if (VERBOSE)
                        System.out.println("    the part exists in the report.");
                    Hashtable hs = (Hashtable) partv.get(partNumber);
                    //更新父件列表
                    Hashtable pathfathers = (Hashtable) hs.get("PATHFATHERS");
                    //pathfathers.put(pathPartNumber,samount);
                    //hs.put("PATHFATHERS",pathfathers);

                    //声明子件BomObject对象
                    BomObject bomobject = null;
                    bomobject = setBomObject(wtPartSon, quantity, lineNumber, partsCache);
                    Hashtable bomInfo = new Hashtable();
                    bomInfo.put("BOMOBJECT", bomobject);
                    bomInfo.put("AMOUNT", samount);
                    pathfathers.put(pathPartNumber, bomInfo);
                    hs.put("PATHFATHERS", pathfathers);

                    //更新总数量
                    Double sumquantity = (Double) hs.get("SUMQUANTITY");
                    sumquantity = new Double(sumquantity.doubleValue() + quantityParent.getAmount() * quantity.getAmount());
                    hs.put("SUMQUANTITY", sumquantity);
                    partv.put(partNumber, hs);
                    traversePartStructure(partNumber, wtPartSon, quantity, partv, level + 1, partsCache);
                }
            }
        }
    }

    /**
     * 输出所有的数据到excel
     **/
    public URL outputDatatoExcel()
        throws WTPropertyVetoException, WTException, RemoteException, IOException, FileNotFoundException
    {
        URL downpath = null;
        String fileName = "";
        try
        {
            if (VERBOSE)
                System.out.println("ReportExporter.OutputDatatoExcel: Begin output data to excel file");

            //复制模板文件
            String orgTemplate = wtProperties.getProperty("ext.generic.bom.template");
            String bomsheetname = wtProperties.getProperty("ext.generic.bom.template.bomsheetname");
            String docsheetname = wtProperties.getProperty("ext.generic.bom.template.docsheetname");
            if (VERBOSE)
                System.out.println("	report template=" + orgTemplate);

            XSSFWorkbook wb = new XSSFWorkbook(orgTemplate);
            XSSFSheet ws = wb.getSheet(bomsheetname);
            //向excel文件中写入数据
            int seq = 0;
            int j = -1;
            XSSFRow row;
            XSSFCell cell;

            if (VERBOSE)
                System.out.println("ReportExporter.OutputDatatoExcel: arraylist.size()=" + arraylist.size());
            if (VERBOSE)
                System.out.println("ReportExporter.OutputDatatoExcel: partv.size()=" + partv.size());
            if (VERBOSE)
                System.out.println("ReportExporter.OutputDatatoExcel: ws.getFirstRowNum() is " + ws.getFirstRowNum());
            if (VERBOSE)
                System.out.println("ReportExporter.OutputDatatoExcel: ws.getLastRowNum() is " + ws.getLastRowNum());

            for (int i = 0; i < arraylist.size(); i++)
            {
                if (VERBOSE)
                    System.out.println("ReportExporter.OutputDatatoExcel: 计数器 i=：" + i);
                if (VERBOSE)
                    System.out.println("ReportExporter.OutputDatatoExcel: count+step =：" + count + step);
                row = ws.getRow(count + step);
                if (row == null)
                    row = ws.createRow(count + step);
                if (VERBOSE)
                    System.out.println("ReportExporter.OutputDatatoExcel: row 2 is " + row);
                if (VERBOSE)
                    System.out.println("ReportExporter.OutputDatatoExcel: row.getFirstCellNum() is " + row.getFirstCellNum());
                if (VERBOSE)
                    System.out.println("ReportExporter.OutputDatatoExcel: row.getLastCellNum() is " + row.getLastCellNum());

                //部件编号
                String partNumber = (String) arraylist.get(i);
                if (VERBOSE)
                    System.out.println("ReportExporter.OutputDatatoExcel: partNumberPath is " + partNumber);

                Hashtable hs = (Hashtable) partv.get(partNumber);
                /*
				Hashtable bomInfo= new Hashtable();
				bomInfo.put("BOMOBJECT",bomobject);
				bomInfo.put("AMOUNT",samount);
				pathfathers.put(pathPartNumber,bomInfo);
				 */
                /*
				BomObject bomobject = (BomObject)hs.get("BOMOBJECT");
				if(bomobject==null)
					continue;
				*/
                Hashtable pathfathers = (Hashtable) hs.get("PATHFATHERS");
                if (VERBOSE)
                    System.out.println("ReportExporter.OutputDatatoExcel: pathfathers is " + pathfathers);
                Double sumquantity = (Double) hs.get("SUMQUANTITY");

                TreeMap tm = new TreeMap();
                Enumeration enum1 = pathfathers.keys();
                while (enum1.hasMoreElements())
                {
                    Object key = enum1.nextElement(); //parent part number
                    //tm.put(obj,pathfathers.get(obj));
                    Hashtable bomInfo = (Hashtable) pathfathers.get(key);
                    BomObject bomobject = (BomObject) bomInfo.get("BOMOBJECT");
                    Object amount = bomInfo.get("AMOUNT");
                    //BomObject bomobject = (BomObject)hs.get("BOMOBJECT");
                    if (bomobject == null)
                        continue;
                    row = ws.getRow(count + step);
                    if (row == null)
                        row = ws.createRow(count + step);

                    WTPart tempprt = bomobject.getWTPart();
                    String value = "";

                    //序号
                    cell = row.getCell((short) 0);
                    cell.setCellValue(Integer.toString(count));

                    //编号
                    value = bomobject.getSoftType1();
                    cell = row.createCell((short) 1);
                    cell.setCellValue(value);

                    //名称
                    value = bomobject.getSoftType2();
                    cell = row.createCell((short) 2);
                    cell.setCellValue(value);

                    //所属装配代号
                    value = key.toString();
                    cell = row.createCell((short) 3);
                    cell.setCellValue(value);

                    //所属装配数量
                    value = amount.toString();
                    cell = row.createCell((short) 4);
                    cell.setCellValue(value);

                    //本表总数量
                    value = sumquantity.toString();
                    if ((value.lastIndexOf(".0") != -1) && (value.lastIndexOf(".0") + 2) == value.length())
                        value = value.substring(0, value.lastIndexOf(".0"));
                    cell = row.createCell((short) 5);
                    cell.setCellValue(value);

                    //备注
                    value = bomobject.getSoftType6();
                    cell = row.createCell((short) 6);
                    cell.setCellValue(value);

                    //零部件类型
                    value = bomobject.getSoftType7();
                    cell = row.createCell((short) 7);
                    cell.setCellValue(value);

                    //材料
                    value = bomobject.getSoftType8();
                    cell = row.createCell((short) 8);
                    cell.setCellValue(value);

                    //材料标准
                    value = bomobject.getSoftType9();
                    cell = row.createCell((short) 9);
                    cell.setCellValue(value);

                    //材料规格
                    value = bomobject.getSoftType10();
                    cell = row.createCell((short) 10);
                    cell.setCellValue(value);

                    //阶段标识
                    value = bomobject.getSoftType11();
                    cell = row.createCell((short) 11);
                    cell.setCellValue(value);

                    //代号
                    value = bomobject.getSoftType12();
                    cell = row.createCell((short) 12);
                    cell.setCellValue(value);

                    //零件规格
                    value = bomobject.getSoftType13();
                    cell = row.createCell((short) 13);
                    cell.setCellValue(value);

                    //毛坯尺寸
                    value = bomobject.getSoftType14();
                    cell = row.createCell((short) 14);
                    cell.setCellValue(value);

                    //型号
                    value = bomobject.getSoftType15();
                    cell = row.createCell((short) 15);
                    cell.setCellValue(value);

                    //图号
                    value = bomobject.getSoftType16();
                    cell = row.createCell((short) 16);
                    cell.setCellValue(value);

                    //重量
                    value = bomobject.getSoftType17();
                    cell = row.createCell((short) 17);
                    cell.setCellValue(value);

                    //毛重
                    value = bomobject.getSoftType18();
                    cell = row.createCell((short) 18);
                    cell.setCellValue(value);

                    //版本
                    value = bomobject.getSoftType19();
                    cell = row.createCell((short) 19);
                    cell.setCellValue(value);

                    //来源
                    value = bomobject.getSoftType20();
                    cell = row.createCell((short) 20);
                    cell.setCellValue(value);

                    //上下文
                    value = bomobject.getSoftType21();
                    cell = row.createCell((short) 21);
                    cell.setCellValue(value);

                    //更新者
                    value = bomobject.getSoftType22();
                    cell = row.createCell((short) 22);
                    cell.setCellValue(value);

                    //行号
                    value = bomobject.getSoftType23();
                    cell = row.createCell((short) 23);
                    cell.setCellValue(value);
                    
                    //英文名称
                    value = bomobject.getSoftType24();
                    cell = row.createCell((short) 24);
                    cell.setCellValue(value);
                    
                    //工程备注
                    value = bomobject.getSoftType25();
                    cell = row.createCell((short) 25);
                    cell.setCellValue(value);
                    //单位
                    cell = row.createCell((short) 26);
                    cell.setCellValue(bomobject.getQuantity().getUnit().getDisplay(locale));
                    
                    //存储位置
                    value = bomobject.getSoftType26();
                    cell = row.createCell((short) 27);
                    cell.setCellValue(value);
                    
                    //工程物料名称
                    value = bomobject.getSoftType27();
                    cell = row.createCell((short) 28);
                    cell.setCellValue(value);
                    
                    count++;
                }
            }

            if (VERBOSE)
                System.out.println("ReportExporter.OutputDatatoExcel: count = " + count);

            ws = wb.getSheet(docsheetname);
            count = 0;
            for (int i = 0; i < docArraylist.size(); i++)
            {
                if (VERBOSE)
                    System.out.println("ReportExporter.OutputDatatoExcel: 计数器 i=：" + i);
                if (VERBOSE)
                    System.out.println("ReportExporter.OutputDatatoExcel: count+step =：" + count + step);
                row = ws.getRow(count + step);
                if (row == null)
                    row = ws.createRow(count + step);
                //部件编号
                DocObject docobject = (DocObject) docArraylist.get(i);
                if (docobject == null)
                    continue;

                String value = "";

                //序号
                cell = row.getCell((short) 0);
                cell.setCellValue(Integer.toString(count));

                //零部件编码
                value = docobject.getSoftType1();
                cell = row.createCell((short) 1);
                cell.setCellValue(value);

                //零部件名称
                value = docobject.getSoftType2();
                cell = row.createCell((short) 2);
                cell.setCellValue(value);

                //文档名称
                value = docobject.getSoftType3();
                cell = row.createCell((short) 3);
                cell.setCellValue(value);

                //文档编码
                value = docobject.getSoftType4();
                cell = row.createCell((short) 4);
                cell.setCellValue(value);

                //文档类型
                value = docobject.getSoftType5();
                cell = row.createCell((short) 5);
                cell.setCellValue(value);

                //阶段标识
                value = docobject.getSoftType6();
                cell = row.createCell((short) 6);
                cell.setCellValue(value);

                //图幅
                value = docobject.getSoftType7();
                cell = row.createCell((short) 7);
                cell.setCellValue(value);

                //比例
                value = docobject.getSoftType8();
                cell = row.createCell((short) 8);
                cell.setCellValue(value);

                //版本
                value = docobject.getSoftType9();
                cell = row.createCell((short) 9);
                cell.setCellValue(value);

                //更新者
                value = docobject.getSoftType10();
                cell = row.createCell((short) 10);
                cell.setCellValue(value);

                count++;
            }

            //创建excel临时文件
            File file1 = StandardIXBService.getSaveDirectoryOnServer();
            File file2;
            file2 = File.createTempFile("eaie", ".xlsm", file1);
            //结果保存到该文件中
            FileOutputStream fos = new FileOutputStream(file2);
            wb.write(fos);
            fos.flush();
            //构造该文件下载链接
            String s = null;
            String s1 = "report.xlsm";
            String s2 = "-";
            boolean flag = nmcommandbean.getRequestData().getUserAgent().toLowerCase().contains("msie");
            s = s1;
            if (!flag)
            {
                s = s.replaceAll(" ", "_");
            }
            if (VERBOSE)
                System.out.println("    download file name=" + s);
            downpath = constructOutputURL(file2, s);
        }
        catch (Exception e)
        {
            System.out.println(e);
        }

        if (VERBOSE)
            System.out.println("ReportExporter.OutputDatatoExcel: End output data to excel file");
        return downpath;
    }

    //获得相关文档
    //需要记录的软属性:
    //SoftType1:零部件编码
    //SoftType2:零部件名称
    //SoftType3:文档名称
    //SoftType4:文档编码
    //SoftType5:文档类型
    //SoftType6:阶段标识
    //SoftType7:图幅
    //SoftType8:比例
    //SoftType9:版本

    public DocObject setDocObject(WTObject obj, String pNumber, String pName)
        throws WTException, VersionControlException, RemoteException
    {
        DocObject docobject = new DocObject();
        String value = "";
        WTDocument doc = null;
        EPMDocument epmdoc = null;
        if (obj instanceof WTDocument)
        {
            doc = (WTDocument) obj;
            docobject.setWTDocument(doc);
            //零部件编码
            docobject.setSoftType1(pNumber);
            //零部件名称
            docobject.setSoftType2(pName);
            //文档名称
            docobject.setSoftType3(doc.getName());
            //文档编码
            docobject.setSoftType4(doc.getNumber());
            //文档类型
            value = wt.type.ClientTypedUtility.getLocalizedTypeName(doc, locale);
            docobject.setSoftType5(value);
            //阶段标识
            value = "";
            docobject.setSoftType6(value);
            //图幅
            value = (String) IBAUtil.getIBAValue(doc, "TEMPLATE");
            docobject.setSoftType7(value);
            //比例
            //value =  ext.generic.iba.IBAHelper.getIBAStringValue(doc, "SCALE");
            value = "";
            docobject.setSoftType8(value);
            //版本
            docobject.setSoftType9(VersionControlHelper.getVersionIdentifier(doc).getValue() + "." +
                                   VersionControlHelper.getIterationIdentifier(doc).getValue());
            //更新者
            docobject.setSoftType10(doc.getModifierFullName());
        }
        if (obj instanceof EPMDocument)
        {
            epmdoc = (EPMDocument) obj;
            //零部件编码
            docobject.setSoftType1(pNumber);
            //零部件名称
            docobject.setSoftType2(pName);
            //文档名称
            docobject.setSoftType3(epmdoc.getName());
            //文档编码
            docobject.setSoftType4(epmdoc.getNumber());
            //文档类型
            value = epmdoc.getAuthoringApplication().getDisplay(locale) + " " + epmdoc.getDocType().getDisplay(locale);
            docobject.setSoftType5(value);

            Hashtable ibaValues = IBAUtil.getIBAValues(epmdoc);
            //阶段标识
            String mark1 = (String) ibaValues.get("PHASE_MARK_A");
            String mark2 = (String) ibaValues.get("PHASE_MARK_B");
            String mark3 = (String) ibaValues.get("PHASE_MARK_C");
            if (mark1 == null || mark1.length() <= 0 || mark1.equals("-"))
                mark1 = "";
            if (mark2 == null || mark2.length() <= 0 || mark2.equals("-"))
                mark2 = "";
            if (mark3 == null || mark3.length() <= 0 || mark3.equals("-"))
                mark3 = "";
            value = mark1 + mark2 + mark3;
            docobject.setSoftType6(value);
            //图幅
            value = (String) ibaValues.get("TEMPLATE");
            docobject.setSoftType7(value);
            //比例
            docobject.setSoftType8("");
            //版本
            docobject.setSoftType9(VersionControlHelper.getVersionIdentifier(epmdoc).getValue() + "." +
                                   VersionControlHelper.getIterationIdentifier(epmdoc).getValue());
            //更新者
            docobject.setSoftType10(epmdoc.getModifierFullName());
        }
        return docobject;
    }

    /**
     * 获得子件的方法改写为使用BomObject获得;需要记录的软属性
     */
    public BomObject setBomObject(WTObject obj, Quantity quantity, LineNumber lineNumber, Hashtable partsCache)
        throws WTException, VersionControlException, RemoteException
    {
        BomObject bomobject = new BomObject();
        String value = "";
        WTPart part = null;
        if (obj instanceof WTPart)
        {
            part = (WTPart) obj;
            bomobject.setWTPart(part);
            bomobject.setQuantity(quantity);
            //编号
            bomobject.setSoftType1(part.getNumber());
            //名称
            bomobject.setSoftType2(part.getName());
            //所属装配代号
            bomobject.setSoftType3("");
            //所属装配数量
            bomobject.setSoftType4("");
            //本表总数量
            bomobject.setSoftType5("");
            
            Hashtable ibaValues= (Hashtable)partsCache.get(part.toString()+ "_IBA");
            if(ibaValues==null)
            {
                ibaValues = IBAUtil.getIBAValues(part);
                partsCache.put(part.toString()+ "_IBA", ibaValues);
            }
            else
            {
                if(VERBOSE)
                    System.out.println("    got part iba values from the cache.");
            }
            //备注
            value = (String) ibaValues.get("COMMENT");
            bomobject.setSoftType6(value);
            //零部件类型
            value= (String)partsCache.get(part.toString()+ "_CLF");
            if(value==null)
            {
                value = getPartClassificationName(part);;
                partsCache.put(part.toString()+ "_CLF", value);
            }
            else
            {
                if(VERBOSE)
                    System.out.println("    got part classification node from the cache.");
            }
            bomobject.setSoftType7(value);
            //材料
            value = (String) ibaValues.get("MATERIAL");
            bomobject.setSoftType8(value);
            //材料标准   材料牌号
            value = (String) ibaValues.get("MATERIAL_CODE");
            bomobject.setSoftType9(value);
            //材料规格
            value = (String) ibaValues.get("MATERIAL_NORM");
            bomobject.setSoftType10(value);

            //阶段标识
            String mark1 = (String) ibaValues.get("PHASE_MARK_A");
            String mark2 = (String) ibaValues.get("PHASE_MARK_B");
            String mark3 = (String) ibaValues.get("PHASE_MARK_C");
            if (mark1 == null || mark1.length() <= 0 || mark1.equals("-"))
                mark1 = "";
            if (mark2 == null || mark2.length() <= 0 || mark2.equals("-"))
                mark2 = "";
            if (mark3 == null || mark3.length() <= 0 || mark3.equals("-"))
                mark3 = "";
            value = mark1 + mark2 + mark3;
            bomobject.setSoftType11(value);
            //代号
            value = (String) ibaValues.get("CODENAME");
            bomobject.setSoftType12(value);
            //零件规格
            value = (String) ibaValues.get("PROCESS_SPEC");
            bomobject.setSoftType13(value);
            //毛坯尺寸
            value = (String) ibaValues.get("BLANK_SIZE");
            bomobject.setSoftType14(value);
            //型号
            value = (String) ibaValues.get("MODEL_NUMBER");
            bomobject.setSoftType15(value);
            //图号
            value = (String) ibaValues.get("DRAWING_NO");
            bomobject.setSoftType16(value);
            //重量
            value = (String) ibaValues.get("WEIGHT");
            bomobject.setSoftType17(value);
            //毛重
            value = (String) ibaValues.get("GROSS_WEIGHT");
            bomobject.setSoftType18(value);

            //版本
            bomobject.setSoftType19(VersionControlHelper.getVersionIdentifier(part).getValue() + "." +
                                    VersionControlHelper.getIterationIdentifier(part).getValue());
            //来源
            bomobject.setSoftType20(part.getSource().getDisplay(locale));
            //上下文
            bomobject.setSoftType21(part.getContainerName());
            //更新者
            bomobject.setSoftType22(part.getModifierFullName());

            //行号
            if (lineNumber != null)
                bomobject.setSoftType23(lineNumber.toString());
            
            //英文名称
            value = (String) ibaValues.get("ENGLISH_NAME");
            bomobject.setSoftType24(value);
            //工程备注
            value = (String) ibaValues.get("PROJECT_COMMENT");
            bomobject.setSoftType25(value);
            
            //存储位置
            value= (String)partsCache.get(part.toString()+ "_FOLDER");
            if(value==null)
            {
                //value = part.getFolderPath();
                value= part.getLocation();
                partsCache.put(part.toString()+ "_FOLDER", value);
            }
            else
            {
                if(VERBOSE)
                    System.out.println("    got part folder path from the cache.");
            }
            bomobject.setSoftType26(value);
            
            //工程物料名称:如果为空则取物料名称
            value = (String) ibaValues.get("PROJECT_PART_NAME");
            if(value==null || value.equals("-") || value.equals(" "))
                value= part.getName();
            bomobject.setSoftType27(value);
        }
        return bomobject;
    }

    /**
     *获取零部件的分类路径
     * @param part
     * @return
     * @throws WTException
     */
    public String getPartClassificationName(WTPart part)throws WTException
    {
        String value = "";
        Vector clfNodes=  CSMUtil.getClassNodesByPart(part);
        if(clfNodes!=null && clfNodes.size()>0)
        {
            //ClassificationNode clfNode = CSMUtil.getClassNodeByPart(part);
            for(int i=0; i< clfNodes.size(); i++)
            {
                ClassificationNode clfNode = (ClassificationNode)clfNodes.elementAt(i);
                if (VERBOSE)
                    System.out.println("    the part " + part.getIdentity() + " classification node=" + clfNode.getName());
                String nodePath= (String) clfNodePathCache.get(clfNode.toString());
                if (nodePath == null)
                {
                    nodePath = CSMUtil.getClassificationFullPath(clfNode);
                    clfNodePathCache.put(clfNode.toString(), nodePath);
                }
                else
                {
                    if (VERBOSE)
                    {
                        System.out.println("    get classification node path from cache.");
                    }
                }
                if (VERBOSE)
                    System.out.println("    the part " + part.getIdentity() + " classification node path=" + nodePath);
                if(value.length()<=0)
                    value = nodePath;
                else
                    value = value + ";" + nodePath;
            }
            if (VERBOSE)
                System.out.println("    the part " + part.getIdentity() + "----classification path =" + value);
        }
        /*
        else
        {
            value = part.getPartType().getDisplay(locale);
        }
        */
        if (VERBOSE)
            System.out.println("	final part classification path=" + value);
        return value;
    }

    /**
     *为输出的文件构造下载链接
     * @param file
     * @param s
     * @return
     * @throws WTException
     */
    private static URL constructOutputURL(File file, String s)
        throws WTException
    {
        if (VERBOSE)
        {
            System.out.println("Enter constructOutputURL -->");
        }
        try
        {
            WTPrincipal wtprincipal = SessionHelper.manager.getPrincipal();
            String s1 = wtprincipal.getName();
            if (VERBOSE)
            {
                System.out.println((new StringBuilder()).append("userName: ").append(s1).toString());
            }
            HashMap hashmap = new HashMap();
            String s2 = null;
            if (file != null)
            {
                if (VERBOSE)
                {
                    System.out.println((new StringBuilder()).append("tmpFile: ").append(file.getName()).toString());
                }
                s2 = file.getCanonicalPath();
                if (VERBOSE)
                {
                    System.out.println((new StringBuilder()).append("tmpName: ").append(s2).toString());
                }
            }
            else
            {
                throw new NmException("com.ptc.netmarkets.nmixb.nmixbResource", "6262", null);
            }
            hashmap.put("fname", s2);
            hashmap.put("userName", s1);
            if (VERBOSE)
            {
                System.out.println("securing the download operation");
            }
            SessionContext sessioncontext = new SessionContext();
            sessioncontext.register();
            String s3 = sessioncontext.getSessionId();
            if (s3 == null)
            {
                throw new NmException("com.ptc.netmarkets.nmixb.nmixbResource", "6263", null);
            }
            if (VERBOSE)
            {
                System.out.println((new StringBuilder()).append("sessId: ").append(s3).toString());
            }
            hashmap.put("sessId", s3);
            if (VERBOSE)
            {
                System.out.println((new StringBuilder()).append("fname: ").append(s).toString());
                System.out.println("Done securing the download operation");
            }
            URLFactory urlfactory = new URLFactory();
            URL url =
                GatewayServletHelper.buildAuthenticatedURL(urlfactory, "com.ptc.netmarkets.actionitem.StandardNmActionItemService", "redirectRecipient",
                                                           s, hashmap);
            if (VERBOSE)
            {
                System.out.println((new StringBuilder()).append("<-- Exit constructOutputURL, url: ").append(url.toExternalForm()).append(", file = ").append(file).toString());
            }
            return url;
        }
        catch (MalformedURLException malformedurlexception)
        {
            throw new NmException(malformedurlexception);
        }
        catch (IOException ioexception)
        {
            throw new NmException(ioexception);
        }
    }

    /**
     *获取当前时间，按照指定的格式输入显示值
     * @param DATE_FORMAT
     * @return
     */
    public static String getCurrentTime(String DATE_FORMAT)
    {
        Locale locale = WTContext.getContext().getLocale();
        Calendar calendar = Calendar.getInstance(WTContext.getContext().getTimeZone(), locale);
        java.util.Date datDate = calendar.getTime();
        return WTStandardDateFormat.format(datDate, DATE_FORMAT, locale, calendar.getTimeZone());
    }
}
